const request = require('request');
const config = require('../config/index')
const util = require('../util/util')
const createHash = require('create-hash')
const xml = require('xml2js')
exports.getAccessToken = function (code) {
  let token_url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${config.wx.appId}&secret=${config.wx.appSecret}&code=${code}&grant_type=authorization_code`;
  return new Promise((resolve, reject) => {
    request.get(token_url, function (err, response, body) {
      let result = util.handleResponse(err, response, body);
      resolve(result);
    })
  });
}
exports.getUserInfo = function (access_token, openId) {
  let userinfo = `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openId}&lang=zh_CN`;
  return new Promise((resolve, reject) => {
    request.get(userinfo, function (err, response, body) {
      let result = util.handleResponse(err, response, body);
      resolve(result);
    })
  })
}
exports.getCommonToken = function () {
  let tokenUrl = ` https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.wx.appId}&secret=${config.wx.appSecret}`
  return new Promise((resolve, reject) => {
    request.get(tokenUrl, (err, response, body) => {
      let result = util.handleResponse(err, response, body);
      resolve(result)
    })
  })
}
exports.getTicket = function (access_token) {
  let ticketUrl = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`
  return new Promise((resolve, reject) => {
    request.get(ticketUrl, (err, response, body) => {
      let result = util.handleResponse(err, response, body)
      resolve(result)
    })
  })
}

exports.getPaySign = function (appid, body, nonce_str, notify_url, openid, out_trade_no, spbill_create_ip, total_fee) {
  let params = {
    appid,
    body,
    mch_id: config.mp.mpId,
    nonce_str,
    notify_url,
    openid,
    out_trade_no,
    spbill_create_ip,
    total_fee,
    trade_type: 'JSAPI'
  }
  let str = util.raw(params);
  str += `&key=${config.mp.secret}`
  const sign = createHash('md5').update(str).digest('hex')
  return sign.toUpperCase();
}

exports.getOrderParams = function (appid, body, nonce_str, notify_url, openid, out_trade_no, spbill_create_ip, total_fee, sign) {
  let data = '<xml>' +
    '<appid><![CDATA[' + appid + ']]></appid>' +
    '<body><![CDATA[' + body + ']]></body>' +
    '<mch_id><![CDATA[' + config.mp.mpId + ']]></mch_id>' +
    '<nonce_str><![CDATA[' + nonce_str + ']]></nonce_str>' +
    '<notify_url><![CDATA[' + notify_url + ']]></notify_url>' +
    '<openid><![CDATA[' + openid + ']]></openid>' +
    '<out_trade_no><![CDATA[' + out_trade_no + ']]></out_trade_no>' +
    '<spbill_create_ip><![CDATA[' + spbill_create_ip + ']]></spbill_create_ip>' +
    '<total_fee><![CDATA[' + total_fee + ']]></total_fee>' +
    '<trade_type><![CDATA[JSAPI]]></trade_type>' +
    '<sign><![CDATA[' + sign + ']]></sign>' +
    '</xml>'
  return data
}
exports.UnifiedOrder = function (payparms) {
  let url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'
  return new Promise((resolve, reject) => {
    request.post({ url, method: 'POST', body: payparms }, (err, response, body) => {
      if (!err && response.statusCode == 200) {
        xml.parseString(body.toString('utf-8'), (error, res) => {
          if (!error) {
            let data = res.xml
            console.log(data)
            if (data.return_code[0] == 'SUCCESS' && data.result_code[0] == 'SUCCESS'){
              let prepay_id = data.prepay_id || [];
              let payResult = getPayParams(prepay_id[0]);
              resolve(payResult);
            }
          }
        })
      }
    })
  })
}
function getPayParams(prepay_id){
  let params = {
    appId: config.wx.appId,
    timeStamp: util.createTimeStamp(),
    nonceStr: util.createNonceStr(),
    package: 'prepay_id=' + prepay_id,
    signType: 'MD5'
  }
  let paySign = util.getSign(params, config.mp.secret)
  params.paySign = paySign
  return params
}
